import { provide, inject, readonly as defineReadonly, reactive } from "vue";

export function useProvideInject() {
  /**
   *
   * @param {any} key - 标识
   * @param {any} data - 数据
   * @param {{service:boolean, readonly:boolean}} options - service 是否提供服务，readonly 是否只读
   * @returns
   */
  const createProvide = (key, data, options = {}) => {
    const baseOptions = { service: false, readonly: true };
    const { service, readonly } = Object.assign({}, baseOptions, options);
    if (service) {
      const service = typeof data === "function" ? new data() : data;
      provide(key, service);
      return service;
    } else {
      const state = reactive(data);
      const provideData = readonly ? defineReadonly(state) : state;
      provide(key, provideData);
      return state;
    }
  };

  const useInject = (key, defaultValue = {}) => {
    return inject(key, defaultValue);
  };

  return {
    createProvide,
    useInject,
  };
}
